<!-- AI资源分析 -->
<template>
  <div  class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px; margin-bottom: 32px">
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane key="AI资源分析" label="AI资源分析" name="AI资源分析" lazy>
          <div style="display:flex;justify-content:space-between;">
            <!-- <div class="title">AI资源分析</div> -->
            <div style="display:flex;align-items:center;">
              <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加资源进行AI分析</el-button>
              <div style="color:#2491fc;margin-left:10px;">系统分析完成后会自动加入到邮件跟踪</div>
            </div>
          </div>
          <!-- <div class="btn">
            <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加任务</el-button>
          </div> -->
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
            <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
            <el-table-column label="资源名称" prop="TaskName" align="left" width="500px" show-overflow-tooltip></el-table-column>
            <el-table-column label="编辑时间" prop="TransTime" align="left" width="160px"></el-table-column>
            <el-table-column label="资源来源" prop="FromType" align="left" width="100px">
              <template slot-scope="scope">
                <span v-if="scope.row.FromType === 1">资源导入</span>
                <span v-if="scope.row.FromType === 2">手工添加</span>
              </template>
            </el-table-column>
            <el-table-column label="分析状态" prop="Status" align="left" show-overflow-tooltip>
              <template slot-scope="scope">
                <span style="color:#909399" v-if="scope.row.Status === 0">等待执行</span>
                <span style="color:#409EFF" v-if="scope.row.Status === 1">正在分析</span><!-- {{scope.row.StartTime}} - {{scope.row.EndTime}} 已分析{{scope.row.interval}} -->
                <span style="color:#67C23A" v-if="scope.row.Status === 2">分析成功 {{scope.row.StartTime}} - {{scope.row.EndTime}} 耗时{{scope.row.interval}}</span>
                <span style="color:#F56C6C" v-if="scope.row.Status === 3">分析失败</span>
                <span style="color:#E6A23C" v-if="scope.row.Status === 4">其他错误</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="160px" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="checkMailGlobal(scope.row)">查看</el-button>
                <!-- <el-button size="mini" type="success" @click="changeMailGlobal(scope.row)">修改</el-button> -->
                <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane key="挖掘参数" label="挖掘参数" name="挖掘参数" lazy>
          <mailResources></mailResources>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-dialog title="查看图片" :close-on-press-escape=false :close-on-click-modal="false" :visible.sync="imgdialog" v-el-drag-dialog width="50%">
      <!-- <el-image :src="'data:image/png;base64,' + imgurl" alt=""></el-image> -->
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '导入资源进行AI邮箱分析' : '修改资源' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="600px">
      <el-form label-width="100px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='资源名称:' prop="Descp">
          <el-input v-model="resourceForm.Descp" maxlength="16"></el-input>
        </el-form-item>
        <!-- <el-form-item label='选择文件:'>
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            accept=".txt"
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <span style="color:#909399;margin-left:15px;">请选择txt文件，文件中每行一个企业名称</span>
          </el-upload>
        </el-form-item> -->
        <el-form-item label='资源内容:'>
          <!-- <el-input type="textarea" v-model="resourceForm.resourceContent" :autosize="{ minRows: 5, maxRows:10}"></el-input> -->
          <div style="display:flex; justify-content:flex-end;background:#f5f6fa;padding:10px;border: 1px solid #D3D5E0;">
            <el-upload
            class="upload-demo"
            action="#"
            multiple
            accept=".txt"
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :show-file-list=false
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击导入</el-button>
          </el-upload>
        </div>
        <div class="key-word-textarea flex">
          <!-- <div class="text-area-num-scroll">
            <div class="text-area-num-box" ref="textAreaNumBox" @scroll="sysHandleScroll()">
              <div v-for="(t,i) in textAreaNum" :key="i" class="text-area-num"><span>{{i+1}}</span></div>
            </div>
          </div> -->
          <el-input
            id="text"
            ref="text"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 10}"
            placeholder="文件中每行对应一个企业名称"
            v-model="resourceForm.resourceContent"
            resize="none">
          </el-input>
        </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest } from '@/api/firstPage'
import { parseTime, getuuid } from '@/utils/index.js';
import mailResources from './mailResources'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  components: { mailResources },
directives: { elDragDialog },
data() {
  return {
    pageNum: 1,
    pageSize: 10,
    total: 10,
    activeName: 'AI资源分析',
    fileList: [],
    tableData: [],
    emailForm: {},
    emailList: [],
    imgurl:'',
    ImgBase64: '',
    imgdialog: false,
    dialogVisible: false,
    rules: {
      Descp:[
        { required: true, message: "请输入资源名称"}
      ]
    },
    resourceForm: {},
    Action: 1,
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    addResources(){
      this.Action = 1
      this.resourceForm = {}
      this.$nextTick(() => {
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.Action = 2
      this.resourceForm = {...row}
      this.dialogVisible = true
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.$confirm('此操作将删除该资源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              AutoID: row.AutoID
            }
          }
        }
        const res = await connrequest('EditExactEMail', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const res = await connrequest('GetExactEMailTask')
      let now = Math.round(new Date().getTime()/1000).toString() * 1
      res.Data = res.Data || []
      res.Data.map(item => {
        if(item.Status !== 0){
          let time = item.Status === 1 ? now / 1000 - item.StartTime : item.EndTime - item.StartTime
          let d = Math.floor(time / 3600 / 24) < 1 ? '' : Math.floor(time / 3600 / 24) + '天';
          let h = Math.floor((time  % 86400) / 3600) < 1 ? '' :  Math.floor((time  % 86400) / 3600)  + '小时';
          let m = Math.floor(((time % 86400) % 3600) / 60) < 1 ? '' : Math.floor(((time % 86400) % 3600) / 60)  + '分钟';
          let s = Math.floor(((time % 86400) % 3600) % 60) < 1 ? '' : Math.floor(((time % 86400) % 3600) % 60)  + '秒';
          item.interval = `${d}${h}${m}${s}`;
        }
        item.TransTime = parseTime(item.TransTime)
        item.StartTime = parseTime(item.StartTime)
        item.EndTime = parseTime(item.EndTime)
        return item
      })
      this.tableData = res.Data
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          if(!this.resourceForm.resourceContent){
            this.$message.error('资源内容不能为空')
            return false
          }else{
            let val = this.resourceForm.resourceContent.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '')
            this.$set(this.resourceForm, 'resourceContent', val);
            if(!this.resourceForm.resourceContent){
              this.$message.error('资源内容不能为空')
              return false
            }
            const data = {
              Data:{
                Action: this.Action,
                Detail: {
                  TaskName: this.resourceForm.Descp,
                  Content: Buffer.from(this.resourceForm.resourceContent, 'utf-8').toString('base64')
                },
              }
            }
            const res = await connrequest('EditExactEMail', data)
            if(res.Status.StatusCode === 0){
              this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
              this.dialogVisible = false
              this.getData()
            }
          }
        }
      })
    },
    async checkMailGlobal(row){
      let name = row.FileName.split('/').at(-1)
      window.open(`${row.FromType === 1 ? '/share/海关数据/' + row.TaskName : '/share/' + name}`)
    },
    filechange(file){
      if (!/\.(txt)$/.test(file.name) ) { 
        this.$message.error('请选择txt格式的文件')
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
        return false
      }
      else if(file.size > 50000){
        this.$message.error('请选择小于50k的文档')
        this.$refs['resourceForm'].clearValidate()
        this.fileList = []
        return false
      }
      let that = this
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e)
      {
        that.ImgBase64 = this.result.split(',')[1]
        let resourceContent = Buffer.from(that.ImgBase64, 'base64').toString('utf8')
        resourceContent = resourceContent.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '')
        that.$set(that.resourceForm, 'resourceContent', resourceContent);
        that.fileList = []
      }
    },
    uploadFile(){},
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('文件删除成功')
        this.ImgBase64 = ''
      }
    },
    handleClick(){},
    async handlePreview(file) {
      // const data = {
      //   Data:{
      //     FileName: file.InnerName
      //   }
      // }
      // const res = await downloadfile('DownloadPublicFile', data)
      // let blobUrl = window.URL.createObjectURL(new Blob([res]));
      // const a = document.createElement('a');
      // a.style.display = 'none';
      // a.download = file.InnerName;
      // a.href = blobUrl;
      // a.click();
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.content {
  position: relative;
  margin-top: 25px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
  margin-bottom: 20px;
}
.btn{
  margin: 20px 0;
}


.key-word-textarea {
  height: 170px;
  overflow: hidden;
  box-shadow: 0px -1px 5px 0px rgba(220, 229, 255, 0.7);
  border: 1px solid #D3D5E0;
  border-top: none;
  align-items: flex-start;
  .el-textarea ::v-deep {
    .el-textarea__inner {
      border: none;
      border-radius: 0;
      line-height: 20px;
      font-size: 14px;
      height: 172px !important;
      min-height: 172px !important;
    }
  }
}


.text-area-num-scroll {
  width: 28px;
  overflow: hidden;
  height: 180px;
  background: #F5F6FA;
  padding-top: 5px;
}
.text-area-num-box {
  min-height: 172px;
  overflow-y: auto;
  height: 172px;
  width: 48px;
  padding-bottom: 10px;
}
.text-area-num {
  line-height: 20px;
  width: 28px;
  text-align: center;
}
.flex {
  display: flex;
}
</style>